package com.light.netty.client.handler;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.codec.http.*;
import io.netty.util.CharsetUtil;

public class HttpBusinessClientHandler extends ChannelInboundHandlerAdapter {
    private String name;

    public HttpBusinessClientHandler(String name){
        this.name = name;
    }
    /**
     * 当Channel成功注册到EventLoop上时调用。
     * @param ctx
     * @throws Exception
     */
    @Override
    public void channelRegistered(ChannelHandlerContext ctx) throws Exception {
        System.out.println("HTTP Client Channel registered: " + ctx.channel().id());
    }

    /**
     * 当Channel从EventLoop上取消注册时调用。
     * @param ctx
     * @throws Exception
     */
    @Override
    public void channelUnregistered(ChannelHandlerContext ctx) throws Exception {
        System.out.println("HTTP Client Channel unregistered: " + ctx.channel().id());
    }

    /**
     * 当Channel已经打开并且连接到对端时调用
     * @param ctx
     * @throws Exception
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {

        for (int i = 0; i < 500; i++) {
            int finalI = i;
            FullHttpRequest request = new DefaultFullHttpRequest(
                    HttpVersion.HTTP_1_1,
                    HttpMethod.POST,
                    "/api/resource"
            );

            String msg = name + "HTTP Client: Hello Server" + finalI;
            ByteBuf content = Unpooled.copiedBuffer(msg.getBytes());
            request.headers().set(HttpHeaderNames.HOST, "localhost");
            request.headers().set(HttpHeaderNames.CONTENT_LENGTH, content.readableBytes()); // 添加Content-Length头
            request.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderValues.CLOSE);
            request.content().writeBytes(content);

            ctx.writeAndFlush(request).addListener(future -> {
                if (future.isSuccess()) {
                    System.out.println(name + "HTTP Client Message sent successfully");
                } else {
                    System.err.println(name + "HTTP Client Failed to send message: " + future.cause());
                }
            });
        }
    }

    /**
     * 当Channel连接关闭时调用。
     * @param ctx
     * @throws Exception
     */
    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("HTTP Client Channel inactive: " + ctx.channel().id());
    }

    /**
     * 当Channel中有数据可读时调用。
     * @param ctx
     * @param msg
     * @throws Exception
     */
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        if (msg instanceof FullHttpResponse){
            FullHttpResponse response = (FullHttpResponse) msg;

            // 直接获取请求体内容（ByteBuf 类型）
            ByteBuf content = response.content();
            // 将 ByteBuf 转换为 String（按需处理）
            System.out.println(name + "客户端接收到相应消息： " + content.toString(CharsetUtil.UTF_8));
        }else if (msg instanceof FullHttpRequest){
            FullHttpRequest request = (FullHttpRequest) msg;

            // 直接获取请求体内容（ByteBuf 类型）
            ByteBuf content = request.content();
            // 将 ByteBuf 转换为 String（按需处理）
            System.out.println(name + "客户端接收到请求消息：: " + content.toString(CharsetUtil.UTF_8));
        }else{
            System.out.println(name + "客户端接收到未知消息: " + msg);
        }
    }

    /**
     * 当Channel中的数据已经读取完毕时调用。
     * @param ctx
     * @throws Exception
     */
    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        System.out.println("HTTP Client Channel read complete");
    }

    /**
     * 当Channel的可写状态发生改变时调用。
     * @param ctx
     * @throws Exception
     */
    @Override
    public void channelWritabilityChanged(ChannelHandlerContext ctx) throws Exception {
        System.out.println("HTTP Client Channel writability changed: " + ctx.channel().isWritable());
    }

    /**
     * 用于处理用户自定义的事件。
     * @param ctx
     * @param evt
     * @throws Exception
     */
//    @Override
//    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
//        if (evt instanceof MyCustomEvent) {
//            MyCustomEvent event = (MyCustomEvent) evt;
//            System.out.println("Received custom event: " + event.getMessage());
//        }
//    }

    /**
     * 用于捕获和处理Channel中发生的异常。
     * @param ctx
     * @param cause
     * @throws Exception
     */
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        // 处理异常情况
        cause.printStackTrace();
        ctx.close();
    }
}